<template>
  <div class="login-madal">
    <!-- mask遮罩层 -->
    <div class="mask" @click="shows"></div>
    <!-- 白色盒子 -->
    <div class="login-box">
      <img class="close" src="../assets/img/close.png" @click="shows" alt="" />
      <ul class="title">
        <li :class="isShowForm ? 'active' : ''" @click="isShowForm = true">
          手机号登录
        </li>
        <li class="shu">|</li>
        <li :class="isShowForm ? '' : 'active'" @click="weixinClick">
          微信扫码登录
        </li>
      </ul>
      <div class="body">
        <form v-show="isShowForm">
          <div class="input-group">
            <input
              type="text"
              placeholder="请输入手机号"
              v-model="phoneValue"
            />
          </div>
          <div>
            <slide-verify
              :l="42"
              :r="20"
              :w="362"
              :h="140"
              @success="onSuccess"
              @fail="onFail"
              @refresh="onRefresh"
              :style="{ width: '100%' }"
              class="slide-box"
              ref="slideBlock"
              :slider-text="msg"
            ></slide-verify>
          </div>
          <div class="input-group">
            <input
              type="text"
              placeholder="请输入短信验证码"
              v-model.trim="smsCode"
            />
            <div
              class="btn get-sms-code"
              :class="isShowCount ? 'has-count' : ''"
            >
              <span v-show="!isShowCount" @click="getSMScode">获取验证码</span>
              <span v-show="isShowCount">{{ count }}s</span>
            </div>
          </div>
          <div class="btn" @click="login" v-show="isShowForm">登录</div>
        </form>
        <div id="weixin" v-show="!isShowForm">二维码</div>
      </div>
    </div>
  </div>
</template>

<script>
import { SendSMS, PhoneLoginAPI, BindPhoneAPI } from "@/request/api";
import { mapMutations, mapActions } from "vuex";
import { validatePhoneNumber } from "../utils";
export default {
  data() {
    return {
      //是否展示表单的变量
      isShowForm: true,
      //滑动验证码的文本
      msg: "向右滑动",
      //用户输入的手机号文本
      phoneValue: "13692505307",
      //手机验证码的文本
      smsCode: 856,
      //count 倒计时用的数字
      count: 0,
      maxCount: 60,
      //是否展示倒计时的数字
      isShowCount: false,
    };
  },
  methods: {
    ...mapMutations({
      // 获取vuex 登录模态框 的显示隐藏函数
      show: "handleLoginModal/showLogin",
      // 获取vuex的 改变登录状态函数
      changeIsLogined: "loginstatus/changeIsLogined",

      showLogin: "loginstatus/showLogin",
    }),
    ...mapActions({
      // 自定义 提示框 异步事件
      asyncChangeIsShowToast: "handleToast/asyncChangeIsShowToast",
      // 获取用户信息 异步
      asyncChangeUserInfo: "userInfo/asyncChangeUserInfo",
    }),
    weixinClick() {
      // 点击切换微信扫码登录这一项，并向微信扫码登录
      this.isShowForm = false;

      // 微信登录第一步：申请微信登录二维码
      let _this = this;
      new WxLogin({
        id: "weixin",
        appid: "wx67cfaf9e3ad31a0d", // 这个appid要填死
        scope: "snsapi_login",
        // 扫码成功后重定向的接口
        redirect_uri: "https://sc.wolfcode.cn/cms/wechatUsers/shop/PC",
        // state填写编码后的url
        state: encodeURIComponent(
          window.btoa("http://127.0.0.1:8088" + _this.$route.path)
        ),
        // 调用样式文件
        href: "data:text/css;base64,Lyogd3hsb2dpbi5jc3MgKi8NCi5pbXBvd2VyQm94IC50aXRsZSwgLmltcG93ZXJCb3ggLmluZm97DQogIGRpc3BsYXk6IG5vbmU7DQp9DQoNCi5pbXBvd2VyQm94IC5xcmNvZGV7DQogIG1hcmdpbi10b3A6IDIwcHg7DQp9",
      });
    },
    shows() {
      this.show(false);
    },
    countDown() {
      //把count改回60
      this.count = this.maxCount;
      let timer = setInterval(() => {
        this.count--;
        //每一次count变化的时候，都需要判断count是不是等于0 如果等于0
        if (this.count === 0) {
          //关闭定时器
          clearInterval(timer);
          //显示回 获取验证码
          this.isShowCount = false;
        }
      }, 1000);
    },
    //封装一个公共的代码
    verifyFn() {
      //1.用户输入的手机号是否合法， 不合法就return
      if (!validatePhoneNumber(this.phoneValue)) {
        // alert("请输入正确的手机号");
        this.asyncChangeIsShowToast({
          msg: "请输入正确的手机号",
          type: "warning",
        });
        return true;
      }
      //2.滑块验证码是否通过验证， 没有过就return

      // if (this.msg == "向右滑动" || this.msg == "再试一次") {
      //   // alert("请滑动滑块到正确位置！");
      //   this.asyncChangeIsShowToast({
      //     msg: "请滑动滑块到正确位置！",
      //     type: "warning",
      //   });
      //   return true;
      // }
    },
    async getSMScode() {
      if (this.verifyFn()) return;

      //3.发送短信验证码的请求-- 假如能够成功发起请求，我们还要处理一个倒计时

      //发请求

      // 伪代码
      // SendSMS({
      //   phone:this.phoneValue
      // }).then(res=>{
      //   if(res.code===0){
      //     //业务成功
      //   }else{
      //     //业务失败
      //   }
      // }).catch(err=>{
      //   xxxx
      // })

      let res = await SendSMS({
        phone: this.phoneValue,
      });

      //所有的请求之后都要进行这个业务判断，而且，大部分失败的情况，代码都是一样
      // 所以这个判断要抽取
      // if(res.code===0){
      // console.log(res);
      //发短信成功了，做倒计时
      //   this.isShowCount = true;
      //   this.countDown();
      // }else{
      //   alert(res.message)
      // }

      //判断res是不是false
      if (!res) return;
      //业务成功要执行的代码
      this.asyncChangeIsShowToast({
        msg: res.message,
        type: "warning",
      });
      //显示倒计时
      this.isShowCount = true;
      this.countDown(); //执行倒计时
    },
    async login() {
      //点击登录框

      if (this.verifyFn()) return;

      //3.短信验证码有没有输入
      if (!this.smsCode) {
        // alert("请输入短信验证码");
        this.asyncChangeIsShowToast({
          msg: "请输入短信验证码",
          type: "warning",
        });
        return;
      }

      //4.发送登录请求
      //扫码登录
      let uuid = localStorage.getItem("uuid");
      let res = null;
      if (uuid) {
        //有uuid的情况
        res = await BindPhoneAPI({
          phone: this.phoneValue,
          verifyCode: this.smsCode,
          uuid:uuid,
        });
      } else {
        res = await PhoneLoginAPI({
          verifyCode: this.smsCode,
          phone: this.phoneValue,
        });
      }
      console.log(this.smsCode);
      if (!res) return;
      //登陆成功的逻辑
      // console.log(res);
      //1.提示用户登陆成功
      // alert("登陆成功！");
      this.asyncChangeIsShowToast({
        msg: "登陆成功",
        type: "success",
      });
      //2.关闭登录窗口
      this.show(false);
      //3.保存token值到localStorage
      localStorage.setItem("x-auth-token", res["x-auth-token"]);
      //4.登录状态值切换
      this.changeIsLogined(true);

      //5.清除uuid，清除地址栏上的code
      if (uuid) {
        localStorage.removeItem("uuid");
        //清除地址栏上的code(路由跳转到当前路由即可)
        this.$router.push(this.$route.path);
      }

      //先测试滑块验证码是否通过验证
      //if(滑块验证不通过)
      // if (this.msg == "向右滑动" || this.msg == "再试一次") {
      //   // alert("请滑动滑块到正确位置！");
      //   this.asyncChangeIsShowToast({
      //     msg: "请滑动滑块到正确位置！",
      //     type: "warning",
      //   });
      //   return;
      // }
      // alert("成功了");

      //登录成功之后，获取用户信息
      // let res2 = await GetUserInAPI()
      // console.log("用户信息为：",res2);
      this.asyncChangeUserInfo();
    },
    // 拼图成功
    onSuccess(times) {
      let ms = (times / 1000).toFixed(1);
      this.msg = "login success, 耗时 " + ms + "s";
    },
    // 拼图失败
    onFail() {
      this.onRefresh(); // 重新刷新拼图
    },
    // 拼图刷新
    onRefresh() {
      this.msg = "再试一次";
    },
  },
};
</script>

<style lang = "less" scoped>
@import url("../assets/styles/global.less");
.login-madal {
  width: 100%;
  height: 100%;
  position: fixed;
  left: 0;
  top: 0;

  .mask {
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
  }
  .login-box {
    width: 555px;
    height: 423px;
    background: url("../assets/img/login-box-bg.png");
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    .title {
      display: flex;
      justify-content: center;
      margin-top: 35px;
      color: #ccc;
      .shu {
        margin: -2px 10px 0;
        cursor: auto;
      }
      .active {
        color: #333;
      }
    }
    .close {
      position: absolute;
      right: 60px;
      top: 15px;
      cursor: pointer;
    }
    .body {
      width: 360px;
      margin: 0 auto;
      padding-top: 25px;

      form {
        .input-group {
          display: flex;
          justify-content: space-between;
          margin-bottom: 20px;
          margin-top: 15px; /*新添加*/
          input {
            height: 46px;
            flex: 1;
            text-indent: 10px;
            border: 1px solid #ccc;
            /* box-sizing: border-box; */
          }
        }
        .get-sms-code {
          width: 80px;
          padding: 0 10px;
          margin-left: 10px;
        }
        .btn {
          height: 50px;
          line-height: 50px;
          text-align: center;
          background-color: @base-color;
          color: #fff;
          cursor: pointer;
        }
        .has-count {
          background-color: #ccc;
        }
      }
    }
  }
}

/deep/.slide-box {
  width: 100%;
  position: relative;
  box-sizing: border-box;
  canvas {
    position: absolute;
    left: 0;
    top: -120px;
    display: none;
    width: 100%;
    box-sizing: border-box;
  }
  .slide-verify-block {
    width: 85px;
    height: 136px;
  }
  .slide-verify-refresh-icon {
    top: -120px;
    display: none;
  }
  &:hover {
    canvas {
      display: block;
    }
    .slide-verify-refresh-icon {
      display: block;
    }
  }
  .slide-verify-slider {
    margin-top: 0;
  }
}
#weixin {
  display: flex;
  justify-content: center;
  margin-top: -10px;
}
</style>